import time
from selenium.webdriver.common.by import By
from base.app.base import BasePage, BaseHandle
from utils import app_swipe_find


# 定义对象库层
class LoginPage(BasePage):
    def __init__(self):
        super().__init__()
        # "我的"按钮 - 使用更精确的定位
        self.my_button = (By.XPATH, "//android.view.View[@text='我的' and @bounds='[552,1144][600,1170]']")
        # 头像元素 - 使用位置定位
        self.phone_button = (By.XPATH, "//android.view.View[@bounds='[80,280][130,322]']")
        # "登录"按钮 - 使用更通用的定位
        self.login_button = (By.XPATH, "//*[contains(@text, '登录') or contains(@content-desc, '登录')]")

    # "我的"按钮
    def find_my_button(self):
        # 打印当前上下文
        print("当前上下文：", self.driver.contexts)
        # 打印所有包含"我的"文本的元素及其属性
        elements = self.driver.find_elements(By.XPATH, "//*[@text='我的']")
        print(f"找到 {len(elements)} 个'我的'元素：")
        for ele in elements:
            try:
                print("text=", ele.get_attribute("text"), 
                      "class=", ele.get_attribute("className"), 
                      "clickable=", ele.get_attribute("clickable"), 
                      "bounds=", ele.get_attribute("bounds"),
                      "enabled=", ele.get_attribute("enabled"),
                      "displayed=", ele.get_attribute("displayed"),
                      "content-desc=", ele.get_attribute("content-desc"))
            except Exception as e:
                print("获取属性失败：", e)
        
        # 尝试直接点击元素
        try:
            element = self.get_element(self.my_button)
            print("找到'我的'按钮：", 
                  "text=", element.get_attribute("text"),
                  "class=", element.get_attribute("className"),
                  "clickable=", element.get_attribute("clickable"),
                  "bounds=", element.get_attribute("bounds"))
            # 点击"我的"按钮
            element.click()
            # 打印当前页面 URL，以确认跳转至 http://mp-toutiao-python.itheima.net/#/user
            print('点击"我的"后，当前页面 URL:', self.driver.current_url)
            return element
        except Exception as e:
            print("使用精确定位查找'我的'按钮失败，尝试其他方式...")
            # 尝试使用坐标点击
            try:
                # 使用 bounds 中的坐标
                x = (552 + 600) // 2  # 中心点 x 坐标
                y = (1144 + 1170) // 2  # 中心点 y 坐标
                print(f"尝试点击坐标 ({x}, {y})")
                self.driver.tap([(x, y)])
                return None  # 返回 None 表示已经点击
            except Exception as e:
                print("坐标点击失败：", e)
                raise

    # 手机图标
    def find_phone_button(self):
        # 只在NATIVE_APP下查找，不切换WEBVIEW
        print("当前上下文：", self.driver.current_context)
        print("当前页面源码（APP 端）:", self.driver.page_source)
        all_elements = self.driver.find_elements(By.XPATH, '//*')
        print(f"页面元素总数: {len(all_elements)}")
        # 1. 先尝试查找带"登录"字样的元素
        try:
            login_btn = self.get_element((By.XPATH, "//*[contains(@text, '登录') or contains(@content-desc, '登录') or contains(@text, 'login') or contains(@content-desc, 'login') ]"))
            print("找到登录按钮/入口：", login_btn)
            return login_btn
        except Exception as e:
            print("未找到带'登录'字样的元素，尝试其他方式...", e)
        # 2. 再尝试查找头像图片（src 或 bounds 特征）
        try:
            avatar = self.get_element((By.XPATH, "//android.view.View[contains(@src, 'toutiao-img.itheima.net')]"))
            print("找到头像图片元素：", avatar)
            return avatar
        except Exception as e:
            print("未找到头像图片元素，尝试其他方式...", e)
        try:
            avatar = self.get_element((By.XPATH, "//android.view.View[@bounds='[80,280][130,322]']"))
            print("找到头像bounds元素：", avatar)
            return avatar
        except Exception as e:
            print("未找到头像bounds元素，尝试遍历所有元素...", e)
        # 3. 遍历所有元素，找最有可能的头像或登录入口
        for ele in all_elements:
            try:
                text = ele.get_attribute("text")
                content_desc = ele.get_attribute("content-desc")
                class_name = ele.get_attribute("className")
                bounds = ele.get_attribute("bounds")
                if (text and ("登录" in text or "login" in text)) or (content_desc and ("登录" in content_desc or "login" in content_desc)):
                    print("遍历找到登录相关元素：", ele)
                    return ele
                if bounds == '[80,280][130,322]':
                    print("遍历找到头像bounds元素：", ele)
                    return ele
            except Exception as e:
                continue
        raise Exception("未能找到头像或登录入口元素，请检查页面结构！")

    # "登录"按钮
    def find_login_button(self):
        try:
            element = self.get_element(self.login_button)
            print("找到登录按钮：",
                  "text=", element.get_attribute("text"),
                  "class=", element.get_attribute("className"),
                  "clickable=", element.get_attribute("clickable"),
                  "bounds=", element.get_attribute("bounds"),
                  "content-desc=", element.get_attribute("content-desc"))
            return element
        except Exception as e:
            print("查找登录按钮失败：", e)
            # 尝试滑动查找
            print("尝试滑动查找登录按钮...")
            root_element = self.driver.find_element(By.XPATH, "//*")
            element = app_swipe_find(self.driver, root_element, self.login_button)
            if element:
                print("滑动找到登录按钮：",
                      "text=", element.get_attribute("text"),
                      "class=", element.get_attribute("className"),
                      "clickable=", element.get_attribute("clickable"),
                      "bounds=", element.get_attribute("bounds"),
                      "content-desc=", element.get_attribute("content-desc"))
                return element
            raise


# 定义操作层
class LoginHandle(BaseHandle):
    def __init__(self):
        self.login_page = LoginPage()

    # "我的"按钮
    def click_my_button(self):
        try:
            element = self.login_page.find_my_button()
            if element is None:
                print("'我的'按钮已通过坐标点击")
                return
            print("尝试点击'我的'按钮...")
            element.click()
            print("'我的'按钮点击成功")
        except Exception as e:
            print("点击'我的'按钮失败：", e)
            raise

    # 手机图标
    def click_phone_button(self):
        try:
            element = self.login_page.find_phone_button()
            print("尝试点击手机图标...")
            element.click()
            print("手机图标点击成功")
        except Exception as e:
            print("点击手机图标失败：", e)
            raise

    # "登录"按钮
    def click_login_button(self):
        try:
            element = self.login_page.find_login_button()
            print("尝试点击登录按钮...")
            element.click()
            print("登录按钮点击成功")
        except Exception as e:
            print("点击登录按钮失败：", e)
            raise


# 定义业务层
class LoginProxy:
    def __init__(self):
        self.login_handle = LoginHandle()

    def go_index(self):
        # 单击"我的"按钮
        self.login_handle.click_my_button()
        time.sleep(2)  # 等待页面响应
        # 单击手机图标
        self.login_handle.click_phone_button()
        time.sleep(2)  # 等待页面响应
        # 单击"登录"按钮
        self.login_handle.click_login_button()
